package repository

import init.InitParams
import org.hibernate.Criteria
import org.hibernate.Session
import org.hibernate.boot.MetadataSources
import org.hibernate.boot.registry.StandardServiceRegistryBuilder
import org.hibernate.criterion.Order

/**
 * @param lambdaTransaction (session: Session)->T
 *        High-level function, the return value will be the return value of the function
 * @return T As same as the return value of lambdaTransaction's
 * Execute based transaction,
 * Strap hibernate based control arguments
 */
fun <T> executeTransaction(lambdaTransaction: (session: Session) -> T): T {
//    val serviceRegistry = StandardServiceRegistryBuilder().configure().build()
//    val sessionFactory = MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory()
//    val session = sessionFactory.openSession()
    val session = InitParams.session
    val transaction = session.beginTransaction()

    val result = lambdaTransaction(session)

    transaction.commit()
    session.clear()
//    session.close()
//    sessionFactory.close()

    return result
}

fun Criteria.sortBy(pageable: Pageable) {
    pageable.direction?.let { dire ->
        pageable.attribute?.let { attr ->
            when (dire) {
                Sort.Direction.ASC -> addOrder(Order.asc(attr))
                Sort.Direction.DESC -> addOrder(Order.desc(attr))
            }
        }
    }
}